﻿using System;
using System.Collections.Concurrent;
using System.Threading;

class Automobile
{
    public bool[] Mark = new bool[5]; // 设备完成状态数组
}

class CarFactory
{
    static readonly int TotalCars = 10; // 总共制作 N 个小汽车
    static readonly int TotalDevices = 5; // 流水线上的设备数量
    static BlockingCollection<Automobile> carQueue = new BlockingCollection<Automobile>(new ConcurrentQueue<Automobile>());

    static void Main(string[] args)
    {
        // 启动制造流水线
        StartProductionLine();

        // 等待所有小汽车制造完成
        Console.ReadLine();
    }

    static void StartProductionLine()
    {
        ThreadPool.QueueUserWorkItem(state =>
        {
            for (int i = 1; i <= TotalCars; i++)
            {
                Automobile car = new Automobile();
                carQueue.Add(car);
                Console.WriteLine($"Car {i} is queued for production.");
            }

            Console.WriteLine("All cars have been queued for production.");
        });

        for (int i = 0; i < TotalDevices; i++)
        {
            ThreadPool.QueueUserWorkItem(ProcessCar);
        }
    }

    static void ProcessCar(object state)
    {
        while (true)
        {
            Automobile car = carQueue.Take(); // 取出下一辆汽车

            for (int i = 0; i < TotalDevices; i++)
            {
                Device device = new Device(i + 1);

                // 第一个设备不需要等待
                if (i != 0)
                {
                    // 等待前一个设备完成工作
                    while (!car.Mark[i - 1])
                    {
                        Thread.Sleep(1000); // 每秒检查一次前一个设备的完成状态
                    }
                }
            

                // 开始工作
                device.ProcessCar(car, i);

                car.Mark[i] = true; // 更新设备完成状态

                if (i == TotalDevices - 1)
                {
                    Console.WriteLine($"Car has completed the entire production process.");
                }
            }
        }
    }
}

class Device
{
    private int Id { get; }

    public Device(int id)
    {
        Id = id;
    }

    public void ProcessCar(Automobile car, int carNumber)
    {
        Console.WriteLine($"Device {Id} is processing car {carNumber + 1}.");
        Thread.Sleep(2000); // 模拟工作
    }
}
